// SPDX-FileCopyrightText: Copyright (c) 2017-2024 slowness GmbH <post@slowtec.de>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Asynchronous TCP client example
use std::env::var;
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
use std::time::Duration;
use thread::sleep;

use chrono::Utc;
use futures_util::future::ok;
use tokio::task;
use tokio_modbus::{Error, Slave};
use tokio_modbus::client::{Context, Reader};
use tokio_modbus::prelude::tcp;
use futures::executor::block_on;
use crate::device::Device::Device;

mod device;

mod db;

#[tokio::main(flavor = "current_thread")]
async fn main() {
    use tokio_modbus::prelude::*;
    let mut handles = Vec::with_capacity(10);
    let devices= device::query::get_all().expect("TODO: panic message");
    let len=devices.len();
    for index in 0..len {
        println!("index {}",index);
        handles.push(tokio::spawn(read_device(&devices[index])));
    }
    for handle in handles {
        handle.await;
    }
}

 async fn read_device2(ip_addr:String, port :String, slave: u8)->Result<Context, Error> {
     let socket_addr =format!("{}:{}", ip_addr, port);//[ip_addr, port].join(":");
     let socket_addr = socket_addr.parse().unwrap();
     let mut ctx = tcp::connect_slave(socket_addr,Slave(slave)).await?;
     loop{
         sleep(Duration::from_millis(900));
         let data = ctx.read_holding_registers(0x0000, 4).await.ok();
         println!("{:?}-{} reading data is: {}'{:?}'",socket_addr,slave,Utc::now(),data);
     }
     // ok()?
}

async fn read_device(device: &Device)->Result<Context, Error> {
    let socket_addr =format!("{}:{}", device.ip, device.port);//[ip_addr, port].join(":");
    let socket_addr = socket_addr.parse().unwrap();
    let mut ctx = tcp::connect_slave(socket_addr,Slave(device.slave_id)).await?;
    loop{
        sleep(Duration::from_millis(900));
        let data = ctx.read_holding_registers(0x0000, 4).await.ok();
        println!("{:?}-{} reading data is: {}'{:?}'",socket_addr,device.slave_id,Utc::now(),data);
    }
    // ok()?
}